const user = require("../../js/user.js");
const wd = require("../../js/window.js");
const jQuery = require("jquery");
const mustache = require("mustache");
// 在主进程中.
const TabGroup = require("electron-tabs");
const shortcut = require("../../js/shortcut.js");
const epointajax = require("../../js/epointajax.js");
const package = require("../../package.json");
var path = require('path');
const {
    ipcRenderer,
    remote
} = require('electron');
const {
    allconfig
} = require(path.join(__dirname, '../../js/config'));

const {
    ipcMain,
    globalShortcut
} = remote;

var $navbar,
    currentuser,
    $userPanelBtn,
    $userPanel,
    $tabcontent,
    $setting,
    $update;


// 配置相关对象
var pagevue, feedbackvue, updatevue,
    keysoptions = [],
    keys = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
        "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"
    ];
jQuery(document).ready(function ($) {

    $navbar = $('#navbar');

    currentuser = user.getUserInfo();
    var rendered = mustache.render($("#usertemplate").html(), currentuser);
    $navbar.prepend(rendered);

    //渲染完成之后再获取对象
    $userPanelBtn = $(".user-panel-btn"),
        $userPanel = $('#user-panel'),
        $tabcontent = $("#tabcontent"),
        $setting = $("#setting"),
        $feedback = $("#feedback"),
        $updatenav = $(".nav-update"),
        $update = $("#update");


    $navbar.on('click', '.nav-icon', function () {
        // 用户下拉列表
        var $this = $(this),
            type = $this.data('type');

        if (type == 'set') {
            $setting.toggleClass("hidden");
        } else if (type == 'about') {
            $feedback.toggleClass("hidden");
        } else if (type == 'update') {
            $update.toggleClass("hidden");
        } else if (type == 'quit') {
            if (confirm("确认退出？")) {
                user.dologout('');
            }
        }
    });




    //左侧图标添加点击事件


    // 隐藏用户面板 true 为隐藏
    function hideUserPanel(flag) {
        $userPanelBtn[flag ? 'removeClass' : 'addClass']('active');
        $userPanel[flag ? 'fadeOut' : 'fadeIn'](150);
    }


    //全屏遮罩去除
    $('body').on('click', function (e) {
        if (!$(e.target).closest('.user-panel, .user-panel-btn').length) {
            hideUserPanel(true);
        }
    });

    //首页放个定时器，刷新token
    user.startRefreshToken();

    //初始化配置vue
    initPage();
    //初始化问题反馈vue
    initFeedback();
    //初始化更新信息
    initUpdate();
});




function initPage() {
    keys.forEach(function (item, index) {
        keysoptions.push({
            value: item,
            label: item
        });
    })
    //渲染列表
    pagevue = new Vue({
        el: '#app',
        data: function () {
            return {
                keysoptions: keysoptions,
                keyname: {
                    showAndmin: "showAndmin"
                },
                form: {
                    key_showAndmin1: "",
                    key_showAndmin2: ""
                }
            }
        },
        methods: {
            saveshowAndmin() {
                shortcut.saveShortcut(this.keyname.showAndmin, remote.getCurrentWindow(), this.form.key_showAndmin1, this.form.key_showAndmin2);
            },
            resetAllshot() {
                shortcut.unregisterAll();
                for (var name in this.form) {
                    this.form[name] = "";
                }
            },
            closesetting() {
                $setting.toggleClass("hidden");
            }
        },
        created: function () {
            //初始化快键键配置项，蠢一点，直接赋值，配置多的话，可以改成遍历
            var cmd = shortcut.getShortcut(this.keyname.showAndmin);
            this.form.key_showAndmin1 = cmd != undefined && cmd.indexOf('+') > 0 ? cmd.split('+')[0] : '';
            this.form.key_showAndmin2 = cmd != undefined && cmd.indexOf('+') > 0 ? cmd.split('+')[1] : '';

            //初始化快键键
            shortcut.initUserShortcut(remote.getCurrentWindow());
        },

    });
}



function initFeedback() {
    //渲染列表
    feedbackvue = new Vue({
        el: '#feedbackapp',
        data: function () {
            return {
                form: {
                    content: "",
                    version: package.version
                }
            }
        },
        methods: {
            addfeedback() {
                epointajax.post(allconfig.serverurl + '/rest/toolsrest/feedback_add', {
                    content: this.form.content,
                    version: this.form.version
                }).then((retinfo) => {
                    if (retinfo.status) {
                        this.$message({
                            message: retinfo.text,
                            type: 'success'
                        });
                        this.form.content = "";
                        $feedback.toggleClass("hidden");
                    }
                }).catch(msg => {
                    console.log(msg);
                });
            },
            closefeedback() {
                this.form.content = "";
                $feedback.toggleClass("hidden");
            }
        },
        created: function () {

        },

    });
}


function initUpdate() {
    //渲染列表
    updatevue = new Vue({
        el: '#updateapp',
        data: function () {
            return {
                form: {
                    noteinfo: "",
                    current: package.version,
                    percentage: 0,
                    speed: 0
                }
            }
        },
        methods: {
            format(percentage) {
                return percentage === 100 ? '已完成' : this.form.percentage + '%(下载速度' + this.form.speed + 'kb/s)';
            },
            startupdate() {
                ipcRenderer.send("checkForUpdate");
            },
            addfeedback() {
                epointajax.post(allconfig.serverurl + '/rest/toolsrest/feedback_add', {
                    content: this.form.content,
                    version: this.form.version
                }).then((retinfo) => {
                    if (retinfo.status) {
                        this.$message({
                            message: retinfo.text,
                            type: 'success'
                        });
                        this.form.content = "";
                        $feedback.toggleClass("hidden");
                    }
                }).catch(msg => {
                    console.log(msg);
                });
            },
            closeupdate() {
                this.form.percentage = 0;
                $update.toggleClass("hidden");
            },
            checkVersion() {
                epointajax.post(allconfig.serverurl + '/rest/toolsrest/version_lastest', {}).then((retinfo) => {
                    //判断返回状态
                    //判断下是否有版本信息
                    //判断和本地是否一致，服务器版本肯定大于本地，不一致的话提示更新。
                    if (retinfo.status && retinfo.custom.versionname.length > 0 && retinfo.custom.versionname != package.version) {
                        console.log(retinfo);
                        updatevue.form.noteinfo = retinfo.custom.noteinfo;
                        $updatenav.toggleClass("hidden");
                    }
                }).catch(msg => {
                    console.log(msg);
                });
            }
        },
        created: function () {
            this.$options.methods.checkVersion();

            //是否立刻安装
            ipcRenderer.on("message", (event, text) => {
                console.log("message:" + text);
                if (text == 'isUpdateNow') {
                    //页面渲染有延迟，延迟2秒，到了100%再弹框
                    setTimeout(function () {
                        if (confirm('现在安装?')) {
                            ipcRenderer.send('updateNow')
                        }
                    }, 2000);
                }
            });
            //下载进度
            ipcRenderer.on("downloadProgress", (event, progressObj) => {
                console.log(progressObj);
                updatevue.form.percentage = parseInt(progressObj.percent);
                updatevue.form.speed = parseInt(progressObj.bytesPerSecond / 1000);
            });
        },

    });
}







let tabGroup = new TabGroup();
//添加一个默认首页
tabGroup.addTab({
    title: "首页",
    src: "../appinfo/appmain/appmain.html",
    visible: true,
    active: true,
    closable: false,
    webviewAttributes: {
        nodeintegration: true, //启动node集成
        nodeintegrationinsubframes: true,
        webpreferences: 'contextIsolation=no'
    },
    ready: function () {
        if (allconfig.debug) {
            setTimeout(function () {
                console.log(tabGroup.getActiveTab().webview.openDevTools());
            }, 1000);
        }
    }
});


//使用主进程监听标签添加事件
ipcMain.on('addTab', (event, obj) => {

    var opened = false,
        title = obj.title,
        url = obj.url;

    //判断路径是否本服务端，执行免登
    if (url.indexOf(allconfig.serverurl) == 0) {
        url = allconfig.serverurl + '/rest/common/addCookie?access_token=' + user.getIMTokenInfo().access_token + '&redirect_uri=' + url;
    }

    //判断路径是否本地的
    if (url.indexOf('http') != 0) {
        url = path.join(__dirname, '../') + url;
    }
    tabGroup.getTabs().forEach(function (item, index) {
        if (url == item.webviewAttributes.src) {
            item.activate();
            opened = true;
            return false;
        }
    });
    if (!opened) {
        tabGroup.addTab({
            title: title,
            src: url,
            visible: true,
            active: true,
            webviewAttributes: {
                nodeIntegration: obj.enablenode == 1, //启动node集成
                allowRunningInsecureContent: true, //允许https加载http
                enableRemoteModule: true, //允许使用remote对象
                webpreferences: 'contextIsolation=no',
                preload: '../../js/tabpreload.js'
            },
            ready: function () {
                if (allconfig.debug) {
                    setTimeout(function () {
                        console.log(tabGroup.getActiveTab().webview.openDevTools());

                        //用户信息编码，传给子页面
                        let jsstr = "window.epointuser='" + encodeURIComponent(JSON.stringify(user.getUserInfo())) + "'";
                        tabGroup.getActiveTab().webview.executeJavaScript(jsstr);
                    }, 1000);
                }
            }
        });
    }
});
